﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ext.Net;
using System.ComponentModel;

namespace Sio.Mdm.Web
{
	public static class Utils
	{
        public static T DeserializeParameter<T>(this Ext.Net.DirectEventArgs e, string keyName)
        {
            if (typeof(T).IsInterface)
            {
                return XML.Deserialize<T>(e.ExtraParams[keyName]);
            }
            else
            {
                object value = e.ExtraParams[keyName];


                if (typeof(T).IsEnum && value != null)
                {
                    return (T)Enum.Parse(typeof(T), value.ToString());
                }

                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                }

                try
                {
                    value = new Guid(value.ToString());
                    return (T)value;
                }
                catch
                {
                }

                throw new InvalidCastException(
                    String.Format("Parameter {0} can not be converted to type {1}",
                    keyName, typeof(T).Name)
                );
            }
        }
        public static T GetValue<T>(this HttpRequest e, string keyName)
        {
            object value = e[keyName];

            try
            {
                if (typeof(T).IsValueType && value == null)
                {
                    return default(T);
                }

                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {   
            }

            try
            {
                if (value != null)
                {
                    value = new Guid(value.ToString());
                    return (T)value;
                }
            }
            catch
            {
            }

            return default(T);
        }
        public static List<T> GetIdList<T>(this Ext.Net.DirectEventArgs e, string keyName, string propertyName)
        {
            string json = e.ExtraParams["selected"];
            Dictionary<string, string>[] rows = JSON.Deserialize<Dictionary<string, string>[]>(json);
            List<T> list = new List<T>();

            foreach (Dictionary<string, string> row in rows)
            {
                foreach (KeyValuePair<string, string> vals in row)
                {
                    if (vals.Key == propertyName)
                    {   
                        list.Add((T) Convert.ChangeType(vals.Value, typeof(T)));
                    }
                }
            }

            return list;
        }
    }
}
